<?php

namespace app\admin\controller;

use app\common\business\WorkCpRecord;
use app\common\business\WorkRob;
use app\common\lib\Param;
use app\common\lib\Show;
use think\response\Json;

class Work extends AdminBase
{
    /**
     * 管理后台列表
     * @return Json
     */
    public function list(): Json
    {
        list($name, $page,$limit,$type,$valuation,$isEnterprise,$isShow,$processStatus,$department) = Param::getMore([
            ['name', ''],
            ['page', 1],
            ['limit', 10],
            ['type', 0],
            ['valuation', 0],
            ['is_enterprise', 0],
            ['is_show', 0],
            ['process_status', null],//0有实际意义，不可默认0
            ['department', 0],
        ], $this->request, true);
        try {
            $list=(new \app\common\business\Work())->getTableList($page,$limit,['name'=>$name,'type'=>$type,'valuation'=>$valuation,'is_enterprise'=>$isEnterprise,'is_show'=>$isShow,'process_status'=>$processStatus,'department'=>$department],$this->departmentId);
            if (!empty($list['list'])){$list['list'] = (new WorkCpRecord())->getRecordWithList($list['list']);}
        }catch (\Exception $e){
            return Show::error([], $e->getMessage(), $e->getCode());
        }
        return Show::success($list);
    }

    /**
     * 零活申请人列表
     * @return Json
     */
    public function applyList(): Json
    {
        list($work_id, $page,$limit,$isEmployed) = Param::getMore([
            ['work_id',null],
            ['page', 1],
            ['limit', 10],
            ['is_employed', 0],
        ], $this->request, true);
        if(empty($work_id)){
            return Show::error([], '零活ID不能为空');
        }
        try {
            $list=(new WorkRob())->getTableJoinList($page,$limit,['work_id'=>$work_id,'is_employed'=>$isEmployed]);
        }catch (\Exception $e){
            return Show::error([], $e->getMessage(), $e->getCode());
        }
        return Show::success($list);
    }

    /**
     * 对应申请者数量
     * @return Json
     */
    public function getEmployedNum(): Json
    {
        list($work_id,$isEmployed) = Param::getMore([
            ['work_id',null],
            ['is_employed', 0],
        ], $this->request, true);
        if(empty($work_id)){
            return Show::error([], '零活ID不能为空');
        }
        $count = (new WorkRob())->getEmployedNum(['work_id'=>$work_id,'is_employed'=>$isEmployed]);
        return Show::success($count);
    }

    /**
     * 抢活
     * @return Json
     */
    public function rob(): Json
    {
        $workId=$this->request->post('work_id');
        $departmentId=$this->departmentId;
        if(empty($departmentId)){
            return Show::error([], '当前角色不是人力资源公司或未绑定人力资源公司');
        }
        try {
            $result = (new \app\common\business\Work())->robWork($workId,$departmentId);
        } catch (\Exception $e) {
            return Show::error([], $e->getMessage(), $e->getCode());
        }
        if ($result) {
            return Show::success([], "抢活成功，请前往“我的零工”查看");
        }
        return Show::error([], '抢活失败');
    }

    /**
     * 录用人员
     * @return Json
     */
    public function employed(): Json
    {
        $ids=$this->request->post('ids');
        $work_id=$this->request->post('work_id');
        if(empty($ids) || intval($work_id) == 0){
            return Show::error([], '参数错误');
        }
        try {
            $result = (new WorkRob())->employed($ids,$work_id);
        } catch (\Exception $e) {
            return Show::error([], $e->getMessage(), $e->getCode());
        }
        if ($result) {
            return Show::success([], "录用成功");
        }
        return Show::error([], '录用失败');
    }

    /**
     * 取消录用人员
     * @return Json
     */
    public function employedCancel(): Json
    {
        $id=$this->request->post('id');
        if(intval($id) == 0){
            return Show::error([], '参数错误');
        }
        try {
            $result = (new WorkRob())->employedCancel($id);
        } catch (\Exception $e) {
            return Show::error([], $e->getMessage(), $e->getCode());
        }
        if ($result) {
            return Show::success([], "取消成功");
        }
        return Show::error([], '取消失败');
    }

    /**
     * 零活改价
     * @return Json
     */
    public function changePrice(){
        list($id, $population,$price,$isShow) = Param::postMore([
            ['id',null],
            ['population',0],
            ['price',0],
            ['is_show',2],
        ], $this->request, true);
        $data=[
            'id'=>$id,
            'population'=>$population,
            'price'=>$price,
            'is_show'=>$isShow,
        ];
        if(empty($this->departmentId)){
            return Show::error([], '仅人力资源公司可修改');
        }

        $validate=new \app\admin\validate\Work();
        if (!$validate->scene('changePrice')->check($data)) {
            return Show::error([], $validate->getError());
        }
        try {
            $result = (new \app\common\business\Work())->changePrice($data,$this->departmentId);
        } catch (\Exception $e) {
            return Show::error([], $e->getMessage(), $e->getCode());
        }
        if ($result) {
            return Show::success([], "修改成功");
        }
        return Show::error([], '修改失败');
    }

    /**
     * 零活延期
     * @return Json
     */
    public function handlerDelay(){
        list($id, $start_time) = Param::postMore([
            ['id',null],
            ['start_time',''],
        ], $this->request, true);

        $data=[
            'id'=>$id,
            'start_time'=>$start_time,
        ];
        if(empty($this->departmentId)){
            return Show::error([], '仅人力资源公司可修改');
        }

        $validate=new \app\admin\validate\Work();
        if (!$validate->scene('delay')->check($data)) {
            return Show::error([], $validate->getError());
        }
        try {
            $result = (new \app\common\business\Work())->updateWorkTime($data,$this->departmentId);
        } catch (\Exception $e) {
            return Show::error([], $e->getMessage(), $e->getCode());
        }
        if ($result) {
            return Show::success([], "修改成功");
        }
        return Show::error([], '修改失败');
    }

    /**
     * 零活完工
     * @return Json
     */
    public function handlerFinish(){
        list($id, $start_time) = Param::postMore([
            ['id',null],
            ['end_time',''],
        ], $this->request, true);

        $data=[
            'id'=>$id,
            'end_time'=>$start_time,
        ];
        if(empty($this->departmentId)){
            return Show::error([], '仅人力资源公司可修改');
        }

        $validate=new \app\admin\validate\Work();
        if (!$validate->scene('finish')->check($data)) {
            return Show::error([], $validate->getError());
        }
        try {
            $result = (new \app\common\business\Work())->updateWorkTime($data,$this->departmentId);
        } catch (\Exception $e) {
            return Show::error([], $e->getMessage(), $e->getCode());
        }
        if ($result) {
            return Show::success([], "修改成功");
        }
        return Show::error([], '修改失败');
    }

    /**
     * 根据ID查询详情
     * @return Json
     */
    public function detail(){
        $id=$this->request->get('id');
        try {
            $data=(new \app\common\business\Work())->getDetailById($id);
        }catch (\Exception $e){
            return Show::error([], $e->getMessage(), $e->getCode());
        }
        return Show::success($data);
    }

    //发布/更新零活信息
    public function handlerSave(){
        if (!$this->request->isPost()) {
            return Show::error([],"非法请求");
        }

        $id = input("id", 0, "intval");
        $type = input("type", 0, "intval");//work_type
        $name = $this->request->param("name", "", "trim");
        $start_time = $this->request->param("start_time", "", "trim");
        $population = input("population", 0, "intval");
        $valuation = input("valuation", 0, "intval");
        $price = $this->request->param("price", "0.00", "trim");
        $duration = $this->request->param("duration", "0.00", "trim");
        $address = $this->request->param("address", "", "trim");
        $longitude = $this->request->param("longitude", "", "trim");
        $latitude = $this->request->param("latitude", "", "trim");
        $describe = $this->request->param("describe", "", "trim");
        $attachment = $this->request->param("attachment", [], "trim");
        $status = input("status", 0, "intval");

        //参数校验
        $data = [
            'id' => $id,
            'type' => $type,
            'name' => $name,
            'start_time' => $start_time,
            'population' => $population,
            'valuation' => $valuation,
            'price' => $price,
            'duration' => $duration,
            'address' => $address,
            'longitude' => $longitude,
            'latitude' => $latitude,
            'describe' => $describe,
            'attachment' => implode(',',$attachment),
            'is_enterprise' => 1, //人力资源企业发布
            'status' => $status,
        ];
        $validate = new \app\api\validate\Work();
        if (!$validate->scene('save')->check($data)) {
            return Show::error([], $validate->getError());
        }

        $bisObj = new \app\common\business\Work();
        try {
            $info = $bisObj->adminSaveData($this->departmentId,$this->adminId,$data);
        } catch (\Exception $e) {
            return Show::error([], $e->getMessage());
        }
        if (!$info) {
            return Show::error([], "保存失败");
        }

        return Show::success([], "保存成功");
    }

    /**
     * 根据id删除
     * @return Json
     */
    public function handlerDelete(): Json
    {
        $id=$this->request->get('id');
        try {
            $result=(new \app\common\business\Work())->adminDeleteData($this->departmentId,$id);
        }catch (\Exception $e){
            return Show::error([], $e->getMessage(), $e->getCode());
        }
        if ($result) {
            return Show::success([], "删除成功");
        }
        return Show::error([], '删除失败');
    }

    /**
     * 计价方式
     * @return Json
     */
    public function getValuationBasis(){
        $valuationBasis = config('work.valuation');
        return Show::success($valuationBasis);
    }
}
